package net.lab1024.sa.base.module.support.minio;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.zip.Deflater;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;

public class JsonCompressor {
    public static String compress(String jsonString) throws IOException {
        byte[] input = jsonString.getBytes(StandardCharsets.UTF_8);
        ByteArrayOutputStream bos = new ByteArrayOutputStream(input.length);
        try (DeflaterOutputStream dos = new DeflaterOutputStream(bos, new Deflater(Deflater.BEST_COMPRESSION), true)) {
            dos.write(input);
        }
        byte[] compressed = bos.toByteArray();
        return Base64.getEncoder().encodeToString(compressed);
    }

    public static String decompress(String compressedJson) throws IOException {
        byte[] decoded = Base64.getDecoder().decode(compressedJson);
        ByteArrayInputStream bis = new ByteArrayInputStream(decoded);
        ByteArrayOutputStream bos = new ByteArrayOutputStream(decoded.length);
        try (InflaterInputStream iis = new InflaterInputStream(bis, new Inflater())) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = iis.read(buffer)) > 0) {
                bos.write(buffer, 0, len);
            }
        }
        return bos.toString(StandardCharsets.UTF_8.name());
    }
}
